package com.yunhui.common;

import java.util.Stack;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;


import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.yunhui.common.evn.GlobalEnvironment;


/**
 * 工具类，将一些变量放入model中，方便velocity模板调用
 * 
 * @author HZS
 *
 */

@ControllerAdvice
class CurrentUserControllerAdvice {

	@Value("${yunhui.admin.urlContext:/admin}")
	private String adminUrlContext;

	@Value("${yunhui.admin.urlPrefix:/admin/}")
	private String adminUrlPrefix;
	

	@Autowired
	private GlobalEnvironment env;

	/**
	 * 将当前用户放入model的currentUser中
	 * 
	 * @param authentication
	 * @return
	 */
	@ModelAttribute("currentUser")
	public UserDetails getCurrentUser(Authentication authentication) {
		return (authentication == null) ? null : (UserDetails) authentication.getPrincipal();
	}

	/**
	 * 将一些属性放入model中，用于在velocity模板中使用
	 * 
	 * @param model
	 */
	@ModelAttribute
	public void populateModel(Model model, HttpServletRequest request) {
		model.addAttribute("viewStack", new Stack<String>()); // 用来保存模板的继承堆栈
		model.addAttribute("adminUrlContext", adminUrlContext); // 管理端的url前缀
		model.addAttribute("adminUrlPrefix", adminUrlPrefix); // 管理端的url前缀
		model.addAttribute("env", env); // 环境变量
	}
}

/*
 * @SuppressWarnings("deprecation")
 * 
 * @Configuration class MvcConfig extends WebMvcConfigurerAdapter {
 * 
 * @Value("${file.local.rootDir}") private String fileLocalDir;
 * 
 * @Value("${environment}") private String environment;
 * 
 *//**
	 * 测试环境中，file直接从本地访问，不通过fileserver
	 *//*
		 * @Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
		 * registry.addResourceHandler("/file/**").addResourceLocations("file:" +
		 * fileLocalDir); } }
		 */